// Controller 
package com.xzy.wxpaydemo.controller;


import com.alibaba.fastjson.JSONObject;
import com.xzy.wxpaydemo.config.WxPayConfig;
import com.xzy.wxpaydemo.service.WxService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;


@RestController
@RequestMapping("/wx")
public class WxOrderController {

    @Autowired
    private WxService wxService;

    @PostMapping("/pay")
//    ("微信支付（小程序JSAPI）")
    public Map wxAdd(HttpServletRequest request,int price,String openId) throws Exception {
        return wxService.doUnifiedOrder(request,price,openId);
    }

    @PostMapping("/notify")
//   ("微信回调")
    public String wxPayNotify(HttpServletRequest request) {
        String resXml = "";
        try {
            InputStream inputStream = request.getInputStream();
            //将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            resXml = sb.toString();
            String result = wxService.payBack(resXml);
            return result;
        } catch (Exception e) {
            System.out.println("微信手机支付失败:" + e.getMessage());
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }
    }


    @GetMapping("/getOpenid/{code}")
//   ("获取微信Openid")
    public String getOpenid(@PathVariable String code) throws IOException {
        //wx接口路径
        String url = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&" +
                "appid=" + WxPayConfig.getAppid() + "&secret=" + WxPayConfig.getSecret() + "&js_code=" + code;
        //使用HttpClient发送请求
//        System.out.println("-------------------------");
//        System.out.println(url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //发送Get请求
        HttpGet request = new HttpGet(url);
        request.addHeader("Content-Type", "application/json");
        //获得响应
        CloseableHttpResponse response = httpclient.execute(request);
        //拿到响应体
        HttpEntity httpEntity = response.getEntity();
        //使用工具转换
        String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(jsonObject);//拿到的所有内容
        String openid = jsonObject.get("openid").toString();
        System.out.println(openid);//拿到的openid
        return openid;
    }
}

